package com.itheima.security;

import com.itheima.health.pojo.Permission;
import com.itheima.health.service.UserService;
import com.itheima.health.vo.RoleVO;
import com.itheima.health.vo.UserVO;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

@Component
public class HealthUserDetailServiceImpl implements UserDetailsService {
    @Reference
    private UserService userService; // dubbo 获取 用户服务  访问数据源
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //  根据账号 查询 当前用户  密码  以及所有  角色和权限 关键字
        //  根据账号   查询当前用户  对应角色 信息   keyword ----  角色对应 所有权限 关键字
        //   涉及 表   t_user_role   t_role    t_role_permisssion   t_permission
        //   1. sql  根据账号 查询用户信息
        //   2、 用户id  ---- 对应角色 ---keyword
         //    3.   角色 id  -----对其权限     keyword----Collection
          UserVO userVO = userService.findUserDetailsByUsername(username);
          if(userVO==null){
              return  null;
          }
        List<GrantedAuthority>  grantedAuthorityList = new ArrayList<GrantedAuthority>(); //  存放当前用户所有的权限和角色关键字
          //  UserVO   账号和密码  keys
        List<RoleVO> roles = userVO.getRoles();
        for (RoleVO role : roles) {
            grantedAuthorityList.add(new SimpleGrantedAuthority(role.getKeyword()));
            List<Permission> permissionList = role.getPermissionSet();
            for (Permission permission : permissionList) {
                grantedAuthorityList.add(new SimpleGrantedAuthority(permission.getKeyword()));
            }
        }
        return new User(username,userVO.getPassword(),grantedAuthorityList);
    }
}
